from __future__ import absolute_import
import os
import random
import logging
from obs import ObsClient, PutObjectHeader
from obs_enum import StorageClassEnum
from conf.conf import (ObsAK, ObsEndpoint, ObsSK, BucketName, ObjectName, Times, StorageClass, FileDir)
obs_client = ObsClient(access_key_id=ObsAK,
                       secret_access_key=ObsSK, server=ObsEndpoint)

logger = logging.getLogger()
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("./conf/init_log.txt")
logger.addHandler(handler)


def fill_obs(bucket_name, object_key, file_dir, storage_class):
    object_list = object_key.split(',')
    for objects in object_list:
        if objects == 'anonymize':
            make_anonymize(bucket_name, file_dir, storage_class)
        elif objects == 'scene':
            make_scene(bucket_name, file_dir, storage_class)


def make_anonymize(bucket_name, file_dir, storage_class):
    if file_dir:
        file_dir += '/anonymize'
    else:
        file_dir = 'anonymize'
    file_name_list = []
    for _, _, files in os.walk(file_dir):
        file_name_list = files
    loop_times = Times
    while loop_times:
        loop_times -= 1
        postfix = random.randint(1, 1000)  # 添加下划线+随机数的后缀
        postfix_str = str(postfix)
        for file_name in file_name_list:
            upload_path = '{}/{}'.format(file_dir, file_name)
            f_name = file_name.rsplit('.', 1)
            new_file_name = '{}/{}_{}.{}'.format(file_dir, f_name[0], postfix_str, f_name[1])
            res = upload_file(bucket_name, new_file_name, upload_path, storage_class)
            if res:
                logger.info(new_file_name)


def make_scene(bucket_name, file_dir, storage_class):
    if file_dir:
        file_dir += '/scene'
    else:
        file_dir = 'scene'
    root_list = []
    for root, dirs, files in os.walk(file_dir):
        if not dirs:  # 到达根目录
            root_list.append(root)
            cur_dir = root.replace('\\', '/')  # os.walk拉出是\ obs目录结构需要/
            loop_times = Times
            while loop_times:
                loop_times -= 1
                postfix = random.randint(1, 1000)  # 添加下划线+随机数的后缀
                postfix_str = str(postfix)
                new_file_name = '{}_{}'.format(cur_dir, postfix_str)
                res = upload_file(bucket_name, new_file_name, cur_dir, storage_class)
                if res:
                    for file in files:
                        upload_name = '{}/{}'.format(new_file_name, file)
                        logger.info(upload_name)


def upload_file(bucket_name, object_key, file_path, storage_class):
    headers = PutObjectHeader()
    headers.storageClass = storage_class
    resp = obs_client.putFile(bucket_name, object_key, file_path, headers=headers)
    if not isinstance(resp, list):
        if resp.status >= 300:
            logger.error("上传obs数据%s失败%s", object_key, resp.errorCode)
            return 0
        return 1
    for result in resp:  # 上传文件夹时，返回的result是tuple的list
        if result[1].status >= 300:
            logger.error("上传obs数据%s失败%s", result[0], resp.errorCode)
            return 0
    return 1


if __name__ == '__main__':
    storageClass = StorageClassEnum[StorageClass].value
    fill_obs(BucketName, ObjectName, FileDir, storageClass)  # 从指定路径上传文件至obs
